package com.scau.hwadee.examination.config.realms;

import com.scau.hwadee.examination.entity.UserInfo;
import com.scau.hwadee.examination.mapper.UserInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.util.ByteSource;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;

/**
 * @author YHX
 * @date 2019/7/28  9:19
 * @description
 */
@Slf4j
public class ShiroRealm extends AuthenticatingRealm {
  @Autowired
  private UserInfoMapper userInfoMapper;

  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    UsernamePasswordToken uptoken = (UsernamePasswordToken) authenticationToken;
    UserInfo userInfo = userInfoMapper.getUserWithoutPassword(uptoken.getUsername());
    DefaultSecurityManager defaultSecurityManager = (DefaultSecurityManager) SecurityUtils.getSecurityManager();
    DefaultSessionManager defaultSessionManager = (DefaultSessionManager) defaultSecurityManager.getSessionManager();
    Collection<Session> sessions = defaultSessionManager.getSessionDAO().getActiveSessions();
    if (userInfo != null) {
      String userMessage = userInfo.getUserName()
        + userInfo.getUserTelephone()
        + userInfo.getUserEmail();
      for (Session session : sessions) {
        Object o = session.getAttribute("userMessage");
        if (o == null) continue;
        log.debug("userMessage from session is " + o.toString());
        if (userMessage.equals(o.toString())) {
//                    log.debug("删除重复的session，删除的sessionID为：" + session.getId());
//                    defaultSessionManager.getSessionDAO().delete(session);
          session.setAttribute("isReLogin", true);
        }
      }
      Object principal = userInfo;
      Object hashedCredentials = userInfo.getUserPassword();
      ByteSource credentialsSalt = ByteSource.Util.bytes(userMessage);
      AuthenticationInfo info = new SimpleAuthenticationInfo(principal, hashedCredentials, credentialsSalt, getName());
      return info;
    } else {
      return null;
    }
  }

  @Test
  public void test() {
    String userMessage = "xjl" +
      "32147896513" +
      "32147896513@abc.com";
    System.out.println((new SimpleHash("MD5", "123456", userMessage, 1024).toString()));
  }
}
